package
{
	import com.google.maps.LatLng;
	import com.google.maps.services.ClientGeocoder;
	import com.google.maps.services.ClientGeocoderOptions;
	import com.google.maps.services.GeocodingEvent;
	
	import flash.events.ProgressEvent;
	import flash.events.ServerSocketConnectEvent;
	import flash.net.ServerSocket;
	import flash.net.Socket;
	import flash.utils.ByteArray;
	
	import mx.collections.ArrayCollection;
	import mx.events.CollectionEvent;
	import mx.events.CollectionEventKind;

	public class Server {
		
		private var _serverSocket:ServerSocket;
		private var _clientSocket:Socket;
		public var locations:ArrayCollection;
		
		public function Server() {
			locations = new ArrayCollection();
		}
		
		public function init():void{
			_serverSocket = new ServerSocket();
			_serverSocket.addEventListener(ServerSocketConnectEvent.CONNECT, onServerSocketConnect);
			_serverSocket.bind(31337, "0.0.0.0");
			_serverSocket.listen();
			trace("服务器成功启动");
		}
		
		private function onServerSocketConnect(event:ServerSocketConnectEvent):void{
			if(_clientSocket != null){
				_clientSocket.removeEventListener(ProgressEvent.SOCKET_DATA, onClientSocketData);
			}
			_clientSocket = event.socket;
			_clientSocket.addEventListener(ProgressEvent.SOCKET_DATA, onClientSocketData, false, 0, true);
			trace("客户端 " + Socket(event.socket).remotePort + " 成功接入！");
		}
		
		private function onClientSocketData(event:ProgressEvent):void{
			var buffer:ByteArray = new ByteArray();
			var mobile:String = null;
			var tsp:String = null;
			var lat:Number = 0;
			var lng:Number = 0;
			var accuracy:Number = 0;
			var previous:Object = null;
			_clientSocket.readBytes(buffer, 0, _clientSocket.bytesAvailable);
			var packet:Packet = new Packet(buffer);
			if(packet.readInt() == 999999){
				mobile = packet.readString();
				tsp = packet.readString();
				lat = packet.readDouble();
				lng = packet.readDouble();
				accuracy = packet.readDouble();
				previous = {mobile: mobile, tsp: tsp, lat: lat, lng: lng, location: null, accuracy: accuracy};
				locations.addItem(previous);
			}else{
				trace(packet.array().toString());
			}
			if(previous ==null) return;
		}
		
		//经纬度转化为地址名称
		private function latlng2Addr(latlng:LatLng):String {
			var retValue:String = null;
			var geo:ClientGeocoder=new ClientGeocoder(new ClientGeocoderOptions({countryCode: 'CN', language: 'zh'}));
			geo.reverseGeocode(latlng);
			geo.addEventListener(GeocodingEvent.GEOCODING_SUCCESS, function(gevt:GeocodingEvent):void{
				var markArr:Array=gevt.response.placemarks;
				var xianArr:Array=String(markArr[0]).split(" @"); //县级
				retValue=xianArr[0].toString();
			});
			geo.addEventListener(GeocodingEvent.GEOCODING_FAILURE, function(gevt:GeocodingEvent):void{
				retValue="未知区域";
			});
			return retValue;
		}
	}
}